package com.aos.eap.activity;

import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aos.eap.R;
import com.aos.eap.adapter.MagazineListAdapter;
import com.aos.eap.base.BaseDialogActivity;
import com.aos.eap.base.Constant;
import com.aos.eap.bean.EqpInfoBean;
import com.aos.eap.bean.MagazineBean;
import com.aos.eap.bean.net.BaseResponseBean;
import com.aos.eap.utils.MyUtils;
import com.aos.eap.utils.NetUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static com.aos.eap.utils.AnimationUtils.arrowAnimation;

public class MFG_WorkBeginActivity extends BaseDialogActivity {


    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.ivInfoArrow)
    ImageView ivInfoArrow;
    @BindView(R.id.llInfoTitle)
    LinearLayout llInfoTitle;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.etBdVersion)
    TextView etBdVersion;
    @BindView(R.id.etAir)
    FreeUI_ClearEditText etAir;
    @BindView(R.id.tvRecipe)
    TextView tvRecipe;
    @BindView(R.id.tvBdId)
    FreeUI_ClearEditText tvBdId;
    @BindView(R.id.tvKeyWenDu)
    TextView tvKeyWenDu;
    @BindView(R.id.llInfo)
    LinearLayout llInfo;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.ivMagazineArrow)
    ImageView ivMagazineArrow;
    @BindView(R.id.llMagazineTitle)
    LinearLayout llMagazineTitle;
    @BindView(R.id.etMagazineId)
    FreeUI_ClearEditText etMagazineId;
    @BindView(R.id.rvMagazineList)
    RecyclerView rvMagazineList;
    @BindView(R.id.llMagazine)
    LinearLayout llMagazine;
    @BindView(R.id.ivMessageArrow)
    ImageView ivMessageArrow;
    @BindView(R.id.llMessageTitle)
    LinearLayout llMessageTitle;
    @BindView(R.id.rvMessageList)
    RecyclerView rvMessageList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.cbCheckAll)
    CheckBox cbCheckAll;
    @BindView(R.id.tvCapNum)
    TextView tvCapNum;
    @BindView(R.id.tvWireNum)
    TextView tvWireNum;
    @BindView(R.id.tvMainQty)
    TextView tvMainQty;


    private MagazineListAdapter magazineListAdapter;
    private EqpInfoBean workBeginBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_begin;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        rvMagazineList.setLayoutManager(new LinearLayoutManager(MFG_WorkBeginActivity.this));
        rvMagazineList.setItemAnimator(new DefaultItemAnimator());
        rvMagazineList.addItemDecoration(new DividerItemDecoration(MFG_WorkBeginActivity.this, 1));

        MyUtils.setEditTextListener(etEqpId, this, s -> MyUtils.setEditTextFocus(etLotId));
        MyUtils.setEditTextListener(etLotId, this, s -> MyUtils.setEditTextFocus(tvBdId));
        MyUtils.setEditTextListener(tvBdId, this, s -> {
            String[] values = s.split(";");
            if (values.length > 1) {
                tvBdId.setText(values[0]);
                etBdVersion.setText(values[1]);
            }
            requestInfoByEqpId();
        });
        MyUtils.setEditTextListener(etAir, this, s -> MyUtils.setEditTextFocus(etMagazineId));
        MyUtils.setEditTextListener(etMagazineId, this, s -> {
            boolean isHave = false;
            for (MagazineBean entity : magazineListAdapter.getData()) {
                if (entity.getMagazineID().equalsIgnoreCase(s)) {
                    isHave = true;
                    break;
                }
            }
            if (isHave) {
                MyUtils.setEditTextFocus(etMagazineId);
                etMagazineId.setText("");
                showToast("编号已存在列表中", false);
            } else {
                MagazineBean magazineBean = new MagazineBean();
                magazineBean.setMagazineID(s);
                magazineListAdapter.addData(0, magazineBean);
//                rvMagazineList.smoothScrollToPosition(0);
                MyUtils.setEditTextFocus(etMagazineId);
                etMagazineId.setText("");
            }
        });
    }

    @Override
    protected void initData() {
        cbCheckAll.setOnCheckedChangeListener((compoundButton, isChecked) -> magazineListAdapter.setAll(isChecked));
        magazineListAdapter = new MagazineListAdapter(null);
        magazineListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        magazineListAdapter.isFirstOnly(true);
        rvMagazineList.setAdapter(magazineListAdapter);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("开始作业");
        freeUI_titleView.setLeftListener(view -> showBackDialog(MFG_WorkBeginActivity.this));
        freeUI_titleView.setRightListener("提交", v -> {
            if (MyUtils.isFastClick()){
                showToast("您点击的太快了",false);
                return;
            }
            if (workBeginBean == null) {
                showToast("未获取到页面信息，请重新扫描设备编号等信息", false);
                MyUtils.setEditTextFocus(etEqpId);
                etEqpId.setText("");
                return;
            }
            String air = etAir.getText().toString().trim();
//            if (FreeApi_StringUtils.isEmpty(air)) {
//                showToast("请输入保护气体流量", false);
//                MyUtils.setEditTextFocus(etAir);
//                return;
//            }
            if (magazineListAdapter.getData().size() == 0) {
                showToast("Magazine列表不能为空", false);
                return;
            }
            JsonObject map = new JsonObject();
            map.addProperty("UserID", Constant.CURRENT_USER);
            map.addProperty("EqpID", workBeginBean.getEqpID());
            map.addProperty("LotID", workBeginBean.getLotID());
            map.addProperty("BDID", workBeginBean.getBDID());
            map.addProperty("BDVer", workBeginBean.getBDVer());
            map.addProperty("RecipeID", workBeginBean.getRecipeID());
            map.addProperty("Step", workBeginBean.getStep());
            map.addProperty("Gas", air);
            map.addProperty("ZoneTemperature", workBeginBean.getZoneTemperature());
            map.add("MagazineList", new JsonParser().parse(new Gson().toJson(magazineListAdapter.getData())).getAsJsonArray());
            requestTrackIn(map);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    private void requestTrackIn(JsonObject map) {
        NetUtils.requestGetNet(this, "EMS_TrackIn", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showToast("提交成功", true);
                    new Handler().postDelayed(MFG_WorkBeginActivity.this::finish, 2000);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_TrackIn");
            }
        });
    }

    private void requestInfoByEqpId() {
        String eqpId = etEqpId.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(eqpId)) {
            showToast("请扫描设备编号", false);
            MyUtils.setEditTextFocus(etLotId);
            return;
        }
        String lotId = etLotId.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(lotId)) {
            showToast("请扫描批次编号", false);
            MyUtils.setEditTextFocus(etLotId);
            return;
        }
        String bdId = tvBdId.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(bdId)) {
            showToast("请扫描BD编号", false);
            MyUtils.setEditTextFocus(tvBdId);
            return;
        }
        JsonObject map = new JsonObject();
        map.addProperty("EqpID", eqpId);
        map.addProperty("LotID", lotId);
        map.addProperty("BDID", bdId);
        map.addProperty("BDVer", etBdVersion.getText().toString());
        NetUtils.requestGetNet(this, "EMS_TrackInLoad", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpInfoBean>>(
                new TypeToken<BaseResponseBean<EqpInfoBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<EqpInfoBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    workBeginBean = response.body().getResponse().getBody();
                    setPageData(workBeginBean);
                } else {
                    workBeginBean = null;
                    setPageData(new EqpInfoBean());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpInfoBean>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_TrackInLoad");
                workBeginBean = null;
                setPageData(new EqpInfoBean());
            }
        });
    }

    private void setPageData(EqpInfoBean workBeginBean) {
        MyUtils.setEditTextFocus(etLotId);
        tvRecipe.setText(workBeginBean.getRecipeID());
        tvKeyWenDu.setText(workBeginBean.getZoneTemperature());
        tvCapNum.setText(workBeginBean.getCapNum());
        tvWireNum.setText(workBeginBean.getWireNum());
        tvMainQty.setText(workBeginBean.getMainQty());
    }

    @OnClick({R.id.tvRemove, R.id.llInfoTitle, R.id.llMagazineTitle, R.id.llMessageTitle})
    public void onViewClicked(View view) {
        if (MyUtils.isFastClick()){
            showToast("您点击的太快了",false);
            return;
        }
        switch (view.getId()) {
            case R.id.tvRemove:
                List<MagazineBean> removeList = new ArrayList<>();
                for (MagazineBean magazineBean : magazineListAdapter.getData()) {
                    if (magazineBean.isSelect()) {
                        removeList.add(magazineBean);
                    }
                }
                if (removeList.size() > 0) {
                    magazineListAdapter.clearPos();
                    magazineListAdapter.getData().removeAll(removeList);
                    magazineListAdapter.notifyDataSetChanged();
                    cbCheckAll.setChecked(false);
                } else {
                    showToast("未勾选，不能移除", false);
                }
                break;
            case R.id.llInfoTitle:
                if (llInfo.getVisibility() == View.VISIBLE) {
                    llInfo.setVisibility(View.GONE);
                    arrowAnimation(ivInfoArrow, 1);
                } else {
                    llInfo.setVisibility(View.VISIBLE);
                    arrowAnimation(ivInfoArrow, 2);
                }
                break;
            case R.id.llMagazineTitle:
                if (llMagazine.getVisibility() == View.VISIBLE) {
                    llMagazine.setVisibility(View.GONE);
                    arrowAnimation(ivMagazineArrow, 1);
                } else {
                    llMagazine.setVisibility(View.VISIBLE);
                    arrowAnimation(ivMagazineArrow, 2);
                }
                break;
            case R.id.llMessageTitle:
                if (rvMessageList.getVisibility() == View.VISIBLE) {
                    rvMessageList.setVisibility(View.GONE);
                    arrowAnimation(ivMessageArrow, 1);
                } else {
                    rvMessageList.setVisibility(View.VISIBLE);
                    arrowAnimation(ivMessageArrow, 2);
                }
                break;
        }
    }
}
